import { useAppStoreWithOut } from '@/store';
import { getSessionStorage } from '@/core/utils/util';
import { Http } from './http';
import { getCookie } from 'qx-util';
import { i18n } from '@/locales';
import { HttpResponse, ILoadingHelper, IParam } from '@/core';
import { AxiosResponse } from 'axios';

/**
 * 拦截器
 *
 * @export
 * @class Interceptors
 */
export class Interceptors {
	/**
	 * 路由对象
	 *
	 * @private
	 * @type {(Router | any)}
	 * @memberof Interceptors
	 */
	private router: any;

	/**
	 *  单列对象
	 *
	 * @private
	 * @static
	 * @type { Interceptors }
	 * @memberof Interceptors
	 */
	private static instance: Interceptors;

	/**
	 * 应用加载助手
	 *
	 * @private
	 * @type {ILoadingHelper}
	 * @memberof Interceptors
	 */
	private readonly appLoadingHelper!: ILoadingHelper;

	/**
	 * Creates an instance of Interceptors.
	 * 私有构造，拒绝通过 new 创建对象
	 *
	 * @memberof Interceptors
	 */
	private constructor(router: any) {
		this.router = router;
		this.appLoadingHelper = App.getAppLoadingHelper();
		this.intercept();
	}

	/**
	 * 获取 Interceptors 单例对象
	 *
	 * @static
	 * @param {Router} route
	 * @param {Store<any>} store
	 * @returns {Interceptors}
	 * @memberof Interceptors
	 */
	public static getInstance(router: any): Interceptors {
		if (!this.instance) {
			this.instance = new Interceptors(router);
		}
		return this.instance;
	}

	/**
	 * 拦截器实现接口
	 *
	 * @private
	 * @memberof Interceptors
	 */
	private intercept(): void {
		Http.getHttp().interceptors.request.use(
			(config: any) => {
				const { getAppData: appData } = useAppStoreWithOut();
				if (appData && appData.context) {
					config.headers['srforgsectorid'] = appData.context.srforgsectorid;
				}
				const Environment = App.getEnvironment();
				if (Environment.SaaSMode) {
					const activeOrgData = getSessionStorage('activeOrgData');
					config.headers['srforgid'] = activeOrgData?.orgid;
					if (!config.headers['srfsystemid']) {
						config.headers['srfsystemid'] = activeOrgData?.systemid;
					}
				}
				if (getCookie('ibzuaa-token')) {
					config.headers['Authorization'] = `Bearer ${getCookie(
						'ibzuaa-token'
					)}`;
				} else {
					// 第三方应用打开免登
					if (sessionStorage.getItem('srftoken')) {
						const token = sessionStorage.getItem('srftoken');
						config.headers['Authorization'] = `Bearer ${token}`;
					}
				}
				config.headers['Accept-Language'] = i18n.global.locale.value;
				if (
					!Object.is(Environment.BaseUrl, '') &&
					!config.url.startsWith('https://') &&
					!config.url.startsWith('http://') &&
					!config.url.startsWith('./assets')
				) {
					config.url = Environment.BaseUrl + config.url;
				}
				// 开启loading
				this.beginLoading();
				this.handleBeforeRequest(config);
				return config;
			},
			(error: any) => {
				return Promise.reject(error);
			}
		);

		Http.getHttp().interceptors.response.use(
			(response: AxiosResponse) => {
				// 关闭loading
				this.endLoading();
				return new HttpResponse(response.data, response);
			},
			(error: any) => {
				// 关闭loading
				this.endLoading();

				error = error ? error : { response: {} };
				const { response: res } = error;
				const { data: _data } = res;
				// 处理异常
				if (res.headers && res.headers['x-ibz-error']) {
					res.data.errorKey = res.headers['x-ibz-error'];
				}
				if (res.headers && res.headers['x-ibz-params']) {
					res.data.entityName = res.headers['x-ibz-params'];
				}
				if (res.status === 401) {
					App.login();
				}
				// if (res.status === 403) {
				//     if (res.data && res.data.status && Object.is(res.data.status, "FORBIDDEN")) {
				//         let alertMessage: string = "非常抱歉，您无权操作此数据，如需操作请联系管理员！";
				//         Object.assign(res.data, { localizedMessage: alertMessage, message: alertMessage });
				//     }
				// }
				// if (res.status === 404) {
				//     this.router.push({ path: '/404' });
				// } else if (res.status === 500) {
				//     this.router.push({ path: '/500' });
				// }
				return new HttpResponse(res.data, res);
			}
		);
	}

	/**
	 * 请求之前处理
	 *
	 * @param {*} config
	 * @return {*}
	 * @memberof Interceptors
	 */
	handleBeforeRequest(config: any) {
		if (config.data) {
			try {
				const handle = (data: IParam = {}) => {
					if (data && data.$DO) {
						delete data.$DO;
					}
				};
				const data = JSON.parse(JSON.stringify(config.data));
				if (!data) {
					return;
				}
				if (Object.prototype.toString.call(data) === '[object Object]') {
					handle(data);
				}
				if (Object.prototype.toString.call(data) === '[object Array]') {
					data.forEach((d: IParam) => {
						handle(d);
					});
				}
				config.data = data;
			} catch (error) {}
		}
	}

	/**
	 * 开始加载
	 *
	 * @private
	 * @memberof Http
	 */
	private beginLoading(): void {
		this.appLoadingHelper.beginLoading();
	}

	/**
	 * 加载结束
	 *
	 * @private
	 * @memberof Http
	 */
	private endLoading(): void {
		this.appLoadingHelper.endLoading();
	}
}
